import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom';
import { NavBar, InfiniteScroll, SearchBar, Card, Button, Tag } from 'antd-mobile'
import styles from './css/search.module.css'
import http from '../../utils/http'

const Search = () => {
  const nav = useNavigate()
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)


  const [searchList, setSearchList] = useState([])
  const [hisList, setHisList] = useState(
    JSON.parse(localStorage.getItem("hisList")) || []
  )
  const [value, setValue] = useState('')
  

  // 请求接口
  const getData = async () => {
    if (value !== "") {
      const res = await http.get("/api/list", { params: { wd: value, page } })
      const { code, data } = res.data
      console.log(data);
      if (code === 200) {
        setSearchList([...searchList, ...data])
        setPage((pre)=>pre +1)
      }

      if (data.length === 0) {
          setHasMore(false)
        }
    }
  }

  useEffect(() => {
    getData()
  }, [])





  // 搜索
  const hanSearch = (val) => {
    setValue(val);

    if (val === "") return


    // 去重
    const newhitList = [...hisList]
    const ind = hisList.lastIndexOf(val)
    if (ind > -1) {
      newhitList.splice(ind, 1)
    }
    newhitList.unshift(val)
    setHisList(newhitList)
    // 存储
    localStorage.setItem("hitList", JSON.stringify(newhitList))
  }


  // 删除历史记录
  const handel = () => {
    setHisList([])
    // 存储
    localStorage.setItem("hitList", JSON.stringify([]))
  }



  return (
    <div>
      <NavBar onBack={() => nav("/")}>
        <SearchBar placeholder='请输入内容' onChange={(val) => hanSearch(val)} />
      </NavBar>
      {/*历史搜索*/}
      <Card title='历史搜索' extra={<Button onClick={() => handel()}>清空历史记录</Button>}>
        {
          hisList.map((item, ind) => {
            return <Tag style={{ margin: 5 }} key={ind}>{item}</Tag>
          })
        }
      </Card>

      {/*渲染搜索列表*/}
      <div className={styles.box}>
        {
          searchList.length > 0 &&
          searchList.map((item, ind) => {
            return <dl key={ind} className={styles.dl}>
              <dt>
                <img src={item.image} alt='' style={{ width: "100px", height: "100px" }} />
              </dt>
              <dd>{item.title}</dd>
              <dd>{item.date}</dd>
              <dd className={styles.price}>￥{item.price}</dd>
            </dl>
          })
        }
      </div>
      <InfiniteScroll loadMore={getData} hasMore={hasMore} />

    </div>
  )
}

export default Search
